package top.lywivan.stack;

/**
 * @author :lyw.ivan
 * @date :Created in 2022/6/3
 * @description :
 * @version: 1.0
 */
public class LinkedListStack<E> {

    //栈中结点个数
    int size;
    //维护头结点
    Node<E> head;

    /**
     * 返回栈中元素个数
     * @return
     */
    public int size() {
        return size;
    }
    /**
     * 判断栈是否为空
     * @return
     */
    public boolean empty() {
        return size==0;
    }
    /**
     * 将元素压入栈
     * @param item 被存入栈的元素
     * @return
     */
    public E push(E item) {
        Node<E> newNode=new Node<>(item,head);
        head=newNode;
        size++;
        return item;
    }
    /**
     * 获取栈顶元素，但并不移除，如果栈空则返回null
     * @return
     */
    public E peek() {
        if(head==null){
            return null;
        }
        return head.val;
    }
    /**
     * 移除栈顶元素并返回，如果栈为空则返回null
     * @return
     */
    public E pop() {
        if(head==null){
            return null;
        }
        Node<E> removeNode=head;
        head=head.next;
        removeNode.next=null;
        size++;
        return removeNode.val;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Node<E> curr=head;
        while (curr!=null){
            sb.append(curr.val).append("->");
            curr=curr.next;
        }
        return sb.append("Null").toString();
    }

    //定义结点类
    private static class Node<E>{
        E val;
        Node<E> next;

        public Node(E val, Node<E> next) {
            this.val = val;
            this.next = next;
        }
    }
}
